file对象使用open函数来创建,close来关闭
打开文件步骤
open打开文件
- 文件操作(读或者写)
close关闭文件
1 2 3 4 5
| import codecs f = codecs.open('1.txt') print(f.read()) f.close
|
codecs这个模块主要是用来解决文件乱码的问题。
open格式为open(filename, mode)其中mode有几个参数需要学习
1 2 3 4 5
| import codecs f = codecs.open('1.txt', 'rb') print(f.read()) f.close
|
1 2 3 4 5 6 7
| import codecs f = codecs.open('1.txt', 'wb') f.write('hello world!') f.writelines(['aaa\n', 'bbb\n','ccc\n']) print(f.read()) f.close
|
1 2 3 4 5 6 7
| import codecs f = codecs.open('1.txt', 'ab') f.write('hello world!') f.writelines(['aaa\n', 'bbb\n','ccc\n']) print(f.read()) f.close
|
file对象常用的函数
file.close()
close()方法用于关闭一个已打开的文件。关闭后不能再进行读写操作,否则会出发ValueError错误。close()方法允许调用多次。
当file对象,被引用到操作另外一个文件时,python会自动断臂之前的file对象。
close()语法
例
1 2 3 4 5 6
| f = open('1.txt', 'wb') print "文件名为: ", f.name f.close()
|
file.fluse()
flush()方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空个缓冲区,不需要是被动的等待输出缓冲区写入。
一般情况下,文件关闭后会自动刷新缓冲区,但有时需要在关闭前刷新,这时就可以使用flush()方法。
flush语法
例
1 2 3 4 5 6 7 8 9
| f = open("1.txt", "wb") print "文件名为: ", f.name f.flush() f.close()
|
file.fileno()
fileno()方法返回一个整型的文件描述符(file descriptor FD 整型),可用于底层操作系统的I/O操作。
fileno()语法
例
1 2 3 4 5 6 7 8 9
| f = open("1.txt", "wb") print "文件名为: ", f.name fid = f.fileno() print "文件描述符为: ", fid f.close()
|
file.isatty()
isatty()方法检测文件是否连接到一个终端设备,如果是返回True,否则返回False。
isatty()语法
例
1 2 3 4 5 6 7 8 9
| f = open("1.txt", "wb") print "文件名为: ", f.name ret = f.isatty() print "返回值 : ", ret f.close()
|
file next()
next()方法在文件使用迭代器时会使用到,在循环中,next()方法会在每次循环中调用,该方法返回文件的下一行,如果到达结尾(EOF),则出发Stoplteration
next()语法
例
1 2 3 4 5 6 7 8 9 10
| f = open("1.txt", "rw+") print "文件名为: ", f.name for index in range(6): line = f.next() print "第 %d 行 - %s" % (index, line) f.close()
|
file.read()
read()方法用于从文件读取指定的字节数,如果未给定或为负则拂去所有。
read()语法
例
1 2 3 4 5 6 7 8 9
| f = open("1.txt", "rw+") print "文件名为: ", f.name line = f.read(10) print "读取的字符串: %s" % (line) f.close()
|
file.readline()
readline()方法用于从文件读取整行,包括\n字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括\n字符。
readline()语法
参数
例
1 2 3 4 5 6 7 8 9 10 11 12
| f = open("1", "rw+") print "文件名为: ", f.name line = f.readline() print "读取第一行 %s" % (line) line = f.readline(5) print "读取的字符串为: %s" % (line) f.close()
|
file.readlines()
readlines()方法用于读取所有行(知道结束符EOF)并返回列表,该列表可以有python的for...in...结构进行处理。如果碰到结束符EOF则返回空字符串。
readlines()语法
例
1 2 3 4 5 6 7 8 9 10
| f = open("1.txt", "r") print "文件名为: ", f.name for line in f.readlines(): line = line.strip() print "读取的数据为: %s" % (line) f.close()
|
file.seek()
seek()方法用于移动文件读取指针到指定位置。
seek()语法
1
| fileobject.seek(offset[, whence])
|
参数
offset:开始的偏移量,也就是代表需要移动偏移的字节数
whence:可选,默认值为0.给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从未见末尾算起。
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| f = open("1.txt", "rw+") print "文件名为: ", f.name line = f.readline() print "读取的数据为: %s" % (line) fo.seek(0, 0) line = f.readline() print "读取的数据为: %s" % (line) f.close()
|
file.tell()
tell()方法返回文件的当前位置,即未见指针当前位置。
tell()语法
1
| fileobject.tell(offset[, whence])
|
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| f = open("1.txt", "rw+") print "文件名为: ", f.name line = f.readline() print "读取的数据为: %s" % (line) pos = f.tell() print "当前位置: %d" % (pos) f.close()
|
file.truncate()
truncate()方法用于截断文件,如果指定了可选参数size,则表示截断文件为size个字符。如果没有指定size,则从当前位置起截断;截断之后size后面的所有字符被删除。
truncate()语法
1
| fileobject.truncate([size])
|
参数
size:可选,如果存在则文件截断为size字节。
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| f = open("1.txt", "r+") print "文件名为: ", f.name line = f.readline() print "读取第一行: %s" % (line) f.truncate() line = f.readline() print "读取数据: %s" % (line) f.close()
|
file.write()
write()方法用于向文件中写入指定字符串。
在文件关闭前或者缓冲区刷新前,字符串内容存储在缓冲区中,这时在文件中是看不到写入的内容的。
write()语法
参数
例
1 2 3 4 5 6 7 8
| f = open("1.txt", "w") print "文件名为: ", f.name str = "hello,world!" f.write( str ) f.close()
|
file.writelines()
writelines()方法用于向文件中写入一序列的字符串。
这一序列字符串可以是由迭代对象产生的,如一个字符串列表。
换行需要制定换行符\n。
writelines()语法
1
| fileobject.writelines([str])
|
参数
例
1 2 3 4 5 6 7 8
| f = open("1.txt", "w") print "文件名为: ", f.name seq = ["hello world!\n", "hello python!\n"] f.writelines( seq ) f.close()
|
file的with用法
有一些任务,可能事先需要设置,事后做清理工作。对于这种场景,Python的with语句提供了一种非常方便的处理方式。一个很好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。
如果不用with语句,代码如下:
1 2 3
| file = open("/tmp/foo.txt") data = file.read() file.close()
|
这里有两个问题:
- 可能忘记关闭文件句柄;
- 文件读取数据发生异常,没有进行任何处理。
下面是处理异常的加强版本:
1 2 3 4 5 6 7 8 9 10 11
| try: f = open('xxx') except: print 'fail to open' exit(-1) try: do something except: do something finally: f.close()
|
虽然这段代码运行良好,但是太冗长了。
这时候就是with一展身手的时候了。除了有更优雅的语法,with还可以很好的处理上下文环境产生的异常。
下面是with版本的代码:
1 2
| with open("/tmp/foo.txt") as file: data = file.read()
|